﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Services;
using DDSC.OracleADO;
using System.Text;
using System.Data;

public partial class krj_document_detail : System.Web.UI.Page
{
[WebMethod]
public static Object getCATEGORY(string DEPT_ID)
{
    dbAccess m_dba = new dbAccess();
    Object results = new Object();
    StringBuilder m_sb = new StringBuilder();

    try
    {
        DataSet ds = null;
        ArrayList m_arrParam = new ArrayList();
        m_sb.Clear();
        m_sb.Append(" select  distinct document_category, document_category || ' ' || document_category_name document_category_name ");
        m_sb.Append(" FROM KRJ_CATEGORY_DOCUMENT A  ");
        m_sb.Append(" Where dept_id = :DEPT_ID and STATUS = 'Y' ");
        m_arrParam.Add(m_dba.GetOracleParam(":DEPT_ID", DEPT_ID));
        
        m_sb.Append(" order by document_category ");
        ds = m_dba.runExecuteQuery("CATEGORY", m_sb.ToString(), m_arrParam);

        if (ds.Tables[0].Rows[0]["ReturnCode"].ToString() == "000")
        {
            results = m_dba.RowsToDictionary(ds.Tables["CATEGORY"], ds.Tables["CATEGORY"].Rows.Count.ToString(), "1");
        }
        else
        {
            if (ds.Tables[0].Rows[0]["ReturnCode"].ToString() == "100")
            {
                results = "error_no";
            }
            else
            {
                results = "error資料讀取錯誤！" + ds.Tables[0].Rows[0]["LogMessage"];
            }
        }
    }
    catch (Exception ex)
    {
        results = "error" + ex.Message;
    }
    return results;
}
[WebMethod]
public static Object getDOCUMENT(string DEPT_ID, string CATEGORY_ID)
{
    dbAccess m_dba = new dbAccess();
    Object results = new Object();
    StringBuilder m_sb = new StringBuilder();

    try
    {
        DataSet ds = null;
        ArrayList m_arrParam = new ArrayList();
        m_sb.Clear();
        m_sb.Append(" select  distinct document_no, document_no || ' ' || document_name document_name ");
        m_sb.Append(" FROM KRJ_CATEGORY_DOCUMENT A  ");
        m_sb.Append(" Where dept_id = :DEPT_ID ");
        m_arrParam.Add(m_dba.GetOracleParam(":DEPT_ID", DEPT_ID));
        m_sb.Append(" and document_category = :CATEGORY_ID ");
        m_arrParam.Add(m_dba.GetOracleParam(":CATEGORY_ID", CATEGORY_ID));
        m_sb.Append(" order by data_seq ");
        ds = m_dba.runExecuteQuery("CATEGORY", m_sb.ToString(), m_arrParam);

        if (ds.Tables[0].Rows[0]["ReturnCode"].ToString() == "000")
        {
            results = m_dba.RowsToDictionary(ds.Tables["CATEGORY"], ds.Tables["CATEGORY"].Rows.Count.ToString(), "1");
        }
        else
        {
            if (ds.Tables[0].Rows[0]["ReturnCode"].ToString() == "100")
            {
                results = "error_no";
            }
            else
            {
                results = "error資料讀取錯誤！" + ds.Tables[0].Rows[0]["LogMessage"];
            }
        }
    }
    catch (Exception ex)
    {
        results = "error" + ex.Message;
    }
    return results;
}
[WebMethod]
public static Object getDATA(string DEPT_ID, string CATEGORY_ID, string DOCUMENT_NO)
{
    dbAccess m_dba = new dbAccess();
    Object results = new Object();
    StringBuilder m_sb = new StringBuilder();

    try
    {
        DataSet ds = null;
        ArrayList m_arrParam = new ArrayList();
        m_sb.Clear();
        m_sb.Append(" select  DEPT_ID ");
        m_sb.Append(" FROM KRJ_DOCUMENT A  ");
        m_sb.Append(" Where dept_id = :DEPT_ID ");
        m_arrParam.Add(m_dba.GetOracleParam(":DEPT_ID", DEPT_ID));
        m_sb.Append(" and document_category = :CATEGORY_ID ");
        m_arrParam.Add(m_dba.GetOracleParam(":CATEGORY_ID", CATEGORY_ID));
        m_sb.Append(" and document_no = :DOCUMENT_NO ");
        m_arrParam.Add(m_dba.GetOracleParam(":DOCUMENT_NO", DOCUMENT_NO));
        ds = m_dba.runExecuteQuery("CATEGORY", m_sb.ToString(), m_arrParam);

        if (ds.Tables[0].Rows[0]["ReturnCode"].ToString() == "000")
        {
            results = "error資料已存在";
        }
        else
        {
            if (ds.Tables[0].Rows[0]["ReturnCode"].ToString() == "100")
            {
                results = " ";
            }
            else
            {
                results = "error資料讀取錯誤！" + ds.Tables[0].Rows[0]["LogMessage"];
            }
        }
    }
    catch (Exception ex)
    {
        results = "error" + ex.Message;
    }
    return results;
}
  protected void Page_Load(object sender, EventArgs e)
  {
      try
      {
          string mode = "";
          mode = (string)Request["mode"];
          if (!Page.IsPostBack)
          {

              DataSet ds = null;
              ds = DBINT();
              if (ds != null && ds.Tables[0].Rows[0]["ReturnCode"] == "000")
              {
                  //DropDownList資料bind入
                  ddldept.DataTextField = "DEPT_NAME";
                  ddldept.DataValueField = "DEPT_ID";
                  ddldept.DataSource = ds.Tables["DEPT"];
                  ddldept.DataBind();
              }
              if (PreviousPage != null)
              {
                  //從前一頁帶入KEY資料
                  //lbl_document_no.Text = PreviousPage.DocumentNo;
                  ddldept.SelectedValue = PreviousPage.DEPT_ID;

                  //ddl_category.SelectedValue = PreviousPage.CATEGORY;
                  //ddl_document.SelectedValue = PreviousPage.DocumentNo;

                  hidcategory.Value = PreviousPage.CATEGORY;
                  hiddocument.Value = PreviousPage.DocumentNo;

                  mode = PreviousPage.Mode;
                  hidMODE.Value = mode;
              }
              switch (mode)
              {
                  case "Insert":
                      btn_save.Visible = false;
                      btn_delete.Visible = false;
                      //lbl_document_no.Text = DateTime.Now.ToString("yyyyMMdd-hhmmss-ff");
                      break;
                  case "View":
                      btn_save.Visible = false;
                      btn_delete.Visible = false;
                      btn_insert.Visible = false;
                      FileUploadDoc.Visible = false;
                      PanelDetail.Enabled = false;
                      break;
                  case "Delete":
                      btn_save.Visible = false;
                      btn_delete.Visible = true;
                      btn_insert.Visible = false;
                      FileUploadDoc.Visible = false;
                      PanelDetail.Enabled = false;
                      break;
                  case "Update":
                      ddldept.Enabled = false;
                      //lbl_document_no.Enabled = false;
                      btn_insert.Visible = false;
                      btn_delete.Visible = false;
                      break;
                  default:
                      break;
              }

              if (mode != "Insert")
              {
                  //Load data from db to control
                  using (KRJEntities dc = new KRJEntities())
                  {
                      var document = dc.KRJ_DOCUMENT.Where(d => d.DEPT_ID == ddldept.SelectedValue && d.DOCUMENT_CATEGORY == hidcategory.Value && d.DOCUMENT_NO == hiddocument.Value).Single();
                      if (document != null)
                      {
                          //ddl_category.SelectedValue = document.DEPT_ID;
                          chk_ISSEQUENCE.Checked = document.ISSEQUENCE == "Y" ? true : false;
                          chk_ISMAIL.Checked = document.ISMAIL == "Y" ? true : false;
                          chk_ISSTATISTICS.Checked = document.ISSTATISTICS == "Y" ? true : false;
                          chk_ISTRANSFORM.Checked = document.ISTRANSFORM == "Y" ? true : false;
                          hl_filepath.NavigateUrl = document.ISPATH;
                          hl_filepath.Text = Path.GetFileName(Server.MapPath(document.ISPATH));
                          txt_UNDERTAKERS.Text = document.UNDERTAKERS;
                      }
                  }
              }

          }
          
          ClientScript.RegisterClientScriptBlock(this.GetType(), "getDept", "<script language='javascript'>$(document).ready(function () {PAGE_LOAD(); }) </script>");
      }
      catch (Exception ex)
      {
          //Response.Write(e.Message);
          lbl_message.Text = ex.Message;

      }
  }
  protected void btn_insert_Click(object sender, EventArgs e)
  {
      try
      {
          if (Page.IsValid)
          {
              using (KRJEntities dc = new KRJEntities())
              {
                  KRJ_DOCUMENT document = new KRJ_DOCUMENT();
                  //vicky 2013/6/26 新增欄位
                  document.DEPT_ID = ddldept.SelectedValue;
                  //document.DOCUMENT_CATEGORY = ddl_category.SelectedValue;
                  //document.DOCUMENT_NO = lbl_document_no.Text;
                  //document.DOCUMENT_NAME = ddl_category.SelectedItem.Text;
                  document.DOCUMENT_CATEGORY = hidcategory.Value;
                  document.DOCUMENT_NO = hiddocument.Value;
                  document.DOCUMENT_NAME = hiddocument_name.Value;


                  document.ISSEQUENCE = chk_ISSEQUENCE.Checked == true ? "Y" : "N";
                  document.ISMAIL = chk_ISMAIL.Checked == true ? "Y" : "N";
                  document.ISSTATISTICS = chk_ISSTATISTICS.Checked == true ? "Y" : "N";
                  document.ISTRANSFORM = chk_ISTRANSFORM.Checked == true ? "Y" : "N";

                  string savepath = Server.MapPath(ConfigurationManager.AppSettings["FormsFilePath"].ToString());
                  FileUtil.UploadMultiFiles(savepath, FileUploadHost);

                  document.ISATTACHMENT = FileUploadDoc.HasFile == true ? "Y" : "N";
                  document.ISPATH = ConfigurationManager.AppSettings["FormsFilePath"].ToString() +
                      Path.GetFileName(FileUploadDoc.PostedFile.FileName).ToLower();
                  document.UPD_DOCUMENT_NO = "000001";
                  document.UNDERTAKERS = txt_UNDERTAKERS.Text;

                  document.CRT_ID = User.Identity.Name;
                  document.CRT_DATE = DateTime.Now.ToString("yyyyMMdd");
                  document.CRT_TIME = DateTime.Now.ToString("hhmmss");
                  document.UPD_ID = User.Identity.Name;
                  document.UPD_DATE = DateTime.Now.ToString("yyyyMMdd");
                  document.UPD_TIME = DateTime.Now.ToString("hhmmss");

                  dc.KRJ_DOCUMENT.Add(document);
                  dc.SaveChanges();
                  ddldept.SelectedValue = "";
                  CommonUtil.DisplayInfoMessage(" 新增成功!", lbl_message);
                  //Response.Redirect("~/Management/Forms/krj_document_detail.aspx?mode=Insert");
              }

          }

      }
      catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
      {
          lbl_message.Text = dbex.Message;
      }
      catch (System.Data.Entity.Infrastructure.DbUpdateException upex)
      {
          lbl_message.Text = upex.GetBaseException().Message;
          if (upex.GetBaseException().Message.ToString().IndexOf("ORA-00001") >= 0)
          {
              lbl_message.Text = "表單資料已存在";
          }
          else
          {
              lbl_message.Text = upex.GetBaseException().Message.ToString();
          }
      }
      catch (Exception ex)
      {
          lbl_message.Text = ex.Message;
      }

  }
  protected void btn_update_Click(object sender, EventArgs e)
  {
    try
    {
      if (Page.IsValid)
      {
        using (KRJEntities dc = new KRJEntities())
        {
          //KRJ_DOCUMENT document = dc.KRJ_DOCUMENT.Where(d => d.DOCUMENT_NO == lbl_document_no.Text).Single();
          KRJ_DOCUMENT document = dc.KRJ_DOCUMENT.Where(d => d.DEPT_ID == ddldept.SelectedValue && d.DOCUMENT_CATEGORY == hidcategory.Value && d.DOCUMENT_NO == hiddocument.Value).Single();
          if (document != null)
          {
            //document.DOCUMENT_CATEGORY = ddl_category.SelectedValue;
            //document.DOCUMENT_NAME = ddl_category.SelectedItem.Text;
            


            document.ISSEQUENCE = chk_ISSEQUENCE.Checked == true ? "Y" : "N";
            document.ISMAIL = chk_ISMAIL.Checked == true ? "Y" : "N";
            document.ISSTATISTICS = chk_ISSTATISTICS.Checked == true ? "Y" : "N";
            document.ISTRANSFORM = chk_ISTRANSFORM.Checked == true ? "Y" : "N";

            if (FileUploadDoc.HasFile)
            {
              string savepath = Server.MapPath(ConfigurationManager.AppSettings["FormsFilePath"].ToString());
              FileUtil.UploadMultiFiles(savepath, FileUploadHost);
              document.ISPATH = ConfigurationManager.AppSettings["FormsFilePath"].ToString() +
                  Path.GetFileName(FileUploadDoc.PostedFile.FileName).ToLower();
              document.ISATTACHMENT = "Y";
            }
            //document.ISATTACHMENT = FileUploadDoc.HasFile == true ? "Y" : document.ISATTACHMENT;
            document.UNDERTAKERS = txt_UNDERTAKERS.Text;
            document.UPD_ID = User.Identity.Name;
            document.UPD_DATE = DateTime.Now.ToString("yyyyMMdd");
            document.UPD_TIME = DateTime.Now.ToString("hhmmss");

            dc.SaveChanges();
          }
        }
        CommonUtil.DisplayInfoMessage("資料更新成功!", lbl_message);
      }

    }
    catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
    {
      CommonUtil.DisplayErrorMessage(dbex.Message, lbl_message);
    }
    catch (Exception ex)
    {
      CommonUtil.DisplayErrorMessage(ex.Message, lbl_message);
    }
  }
  protected void btn_delete_Click(object sender, EventArgs e)
  {
    try
    {
      using (KRJEntities dc = new KRJEntities())
      {
        //var document = dc.KRJ_DOCUMENT.Where(d => d.DOCUMENT_NO == lbl_document_no.Text).Single();
        var document = dc.KRJ_DOCUMENT.Where(d => d.DEPT_ID == ddldept.SelectedValue && d.DOCUMENT_CATEGORY == hidcategory.Value && d.DOCUMENT_NO == hiddocument.Value).Single();
        if (document != null)
        {
          dc.KRJ_DOCUMENT.Remove(document);
          dc.SaveChanges();
          Response.Redirect("~/Management/Forms/krj_document.aspx");
        }
      }
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
    {
      lbl_message.Text = dbex.Message;
    }
    catch (Exception ex)
    {
      lbl_message.Text = ex.Message;
    }
  }
  protected void btn_exit_Click(object sender, EventArgs e)
  {
    Response.Redirect("~/Management/Forms/krj_document.aspx");
  }
  protected DataSet DBINT()
  {
      DataSet ds = null;
      try
      {
          dbAccess m_dba = new dbAccess();
          StringBuilder m_sb = new StringBuilder();
          ArrayList m_arrParam = new ArrayList();
          m_sb.Append(" select distinct A.DEPT_ID , A.DEPT_ID || ' ' || B.DEPT_NAME DEPT_NAME ");
          m_sb.Append(" FROM KRJ_CATEGORY_DOCUMENT A left join mis_dept_ap B on A.DEPT_ID = B.DEPT_ID  ");
          m_sb.Append(" order by A.dept_id ");
          ds = m_dba.runExecuteQuery("DEPT", m_sb.ToString(), m_arrParam);
          

      }
      catch (Exception ex)
      {
          lbl_message.Text = ex.Message;
      }
      return ds;
  }
}